<template>
    <div class="dashboard-container">
        <!-- 必填部分 -->
        <div class="must">
            <el-form :rules="rules" :model="temp" ref="form">
                <!-- 固定头 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="名称" prop="name">
                            <el-input placeholder="请输入名称" v-model="temp.name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="经度" prop="longitude">
                            <el-input placeholder="请输入经度" v-model="temp.longitude"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="纬度" prop="latitude">
                            <el-input placeholder="请输入纬度" v-model="temp.latitude"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="选择城市" prop="cityId">
                            <el-select 
                                filterable 
                                v-model="temp.cityId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="handleChangeCity"
                            >
                                <el-option v-for="item,index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="选择区县" prop="areaId">
                            <el-select 
                                filterable 
                                v-model="temp.areaId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="handleChangeArea"
                            >
                                <el-option v-for="item,index in areaList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="选择街道" prop="areaId">
                            <el-select 
                                filterable 
                                v-model="temp.streetId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                            >
                                <el-option v-for="item,index in jdList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="案例时间" prop="time">
                            <el-date-picker
                                v-model="temp.time"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%;"
                                value-format="timestamp"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <!-- 废弃字段 -->
                    <!-- <el-col :span="8">
                        <el-form-item label="案例面积（㎡）" >
                            <el-input placeholder="请输入案例面积" v-model="temp.area"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="自持率（%）" >
                            <el-input placeholder="请输入自持率" v-model="temp.selfHoldRate"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="案例总价（万元）">
                            <el-input placeholder="请输入案例总价" v-model="temp.totalPrice"></el-input>
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <el-form-item label="案例租金（元/㎡/日）">
                            <el-input placeholder="请输入案例租金" v-model="temp.unitRent"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="详细地址">
                            <el-input 
                                type="textarea"
                                :rows="2"
                                placeholder="请输入详细地址"
                                v-model="temp.detailAddress" 
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="描述">
                            <el-input 
                                type="textarea"
                                :rows="2"
                                placeholder="请输入描述"
                                v-model="temp.description" 
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-button size="mini" @click="handeAddPic" type="primary">上传图片</el-button>
                <el-table :data="temp.files">
                    <el-table-column label="名字" prop="showName"></el-table-column>
                    <el-table-column label="描述" prop="description"></el-table-column>
                    <el-table-column label="预览">
                        <template slot-scope="{row, index}">
                            <el-image 
                                style="width: 100px;" 
                                :src="OSS_BASE_URL + row.url+'?x-oss-process=image/resize,w_100'" 
                                v-if="row.showName.indexOf('.jpg')>-1||row.showName.indexOf('.png')>-1"
                                :preview-src-list="[OSS_BASE_URL + row.url]"
                            ></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" >
                        <template slot-scope="{row, index}">
                            <el-button type="text" @click="downloadFile(row.url, row.showName)">下载</el-button>
                            <el-button type="text" style="color: red;" @click="handleDeleteFile(index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 固定头 -->
                <el-row :gutter="20">
                    <el-col :span="8" >
                        <el-form-item label="交易情况" prop="tradeType">
                            <el-select 
                                filterable 
                                v-model="temp.tradeType" 
                                placeholder="请选择" 
                                style="width: 100%;"
                            >
                                <el-option v-for="item in TransactionSituationList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="用途" prop="propertyType">
                            <el-select 
                                filterable 
                                v-model="temp.propertyType" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="handleChangeTargetType"
                                :disabled="id?true:false"
                            >
                                <el-option v-for="item,index in TARGET_TYPE_LIST" :key="index" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="8" v-if="temp.propertyType==1">
                        <el-form-item label="楼盘">
                            <div style="position: relative;">
                                <el-input v-model="temp.communityName" disabled></el-input>
                                <el-button 
                                    type="primary" style="position: absolute; right: 0;"
                                    @click="handleSelectCommunity"
                                >选择楼盘</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 动态加载的表单 -->
                <el-row :gutter="20">
                    <el-col :span="8" v-for="(item, index) in temp.fields" :key="index" style="height: 106px; overflow: hidden;">
                        <el-form-item  :label="item.field.name" >
                            <!-- 多行输入 -->
                             <div style="width: 100%;" v-if="item.field.showType==1&&item.field.valueType==2">
                                <el-input 
                                    type="textarea"
                                    :rows="2"
                                    v-model="item.stringValue" 
                                    placeholder="请输入"
                                ></el-input>
                             </div>
                            
                            
                            <!-- 单行输入，字符串 -->
                            <el-input 
                                v-model="item.stringValue" 
                                v-if="item.field.showType==0&&item.field.valueType==2"
                                placeholder="请输入"
                            ></el-input>

                            <!-- 单行输入，数字 -->
                            <el-input 
                                type="number"
                                v-model="item.decimalValue" 
                                v-if="item.field.showType==0&&item.field.valueType==0"
                                placeholder="请输入"
                            ></el-input>

                            <!-- 枚举选择 -->
                            <el-select 
                                placeholder="请选择" 
                                v-model="item.enumItemName" 
                                v-if="item.field.showType==4"
                                style="width: 100%;"
                            >
                                <el-option v-for="oItem in item.field.relatedEnum.items" :key="oItem.name" :label="oItem.name" :value="oItem.name"></el-option>
                            </el-select>

                            <!-- 日期选择 -->
                            <el-date-picker
                                v-model="item.longValue"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%;"
                                v-if="item.field.showType==2"
                                value-format="timestamp"
                            >
                            </el-date-picker>

                            <!-- 开关按钮 -->
                            <div v-if="item.field.showType==5" style="width: 100%;padding-top: 50px;">
                                <el-switch
                                    style="display: block"
                                    v-model="item.longValue"  
                                    active-color="#039A92"
                                    :active-value="1"
                                    :inactive-value="0"
                                    active-text="是"
                                    inactive-text="否"
                                >
                                </el-switch>
                            </div>  
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 上传文件 -->
                <el-dialog 
                    :visible="dialogVisible" 
                    :close-on-click-modal="false"
                    @close="dialogVisible=false"
                    title="添加文件" 
                    :model="uploadTemp" 
                >
                    <el-form label-width="80px" size="mini">
                        <el-form-item label="显示名：">
                            <el-input placeholder="请输入显示名" v-model="uploadTemp.showName"></el-input>
                        </el-form-item>
                        <el-form-item label="描述：" >
                            <el-input placeholder="请输入描述" v-model="uploadTemp.description"></el-input>
                        </el-form-item>
                        <el-form-item label="文件：">
                            <!-- 文件上传 -->
                            <el-upload
                                class="upload-demo"
                                :action="OSS_CONFIG.host"
                                :before-upload="hanldeUpload"
                                :on-remove="handleRemove"
                                :on-success="handleAvatarSuccess"  
                                :data="uploadData"
                                :file-list="fileList">
                                <el-button size="small" type="primary">点击上传</el-button>
                                <!-- <div slot="tip" class="el-upload__tip">上传文件不超过2M</div> -->
                            </el-upload>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button type="primary" @click="handleSubmitFile">提交</el-button>
                            <el-button @click="dialogVisible=false">取消</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>

                <!-- 选择楼盘 -->
                <el-dialog
                    :visible="dialogVisibleCommunity" 
                    :close-on-click-modal="false"
                    @close="dialogVisibleCommunity=false"
                    title="选择小区" 
                    top="50px"
                >   
                    <el-select 
                        filterable  
                        clearable v-model="communityParams.cityId" 
                        placeholder="请选择" 
                        size="mini"
                    >
                        <el-option v-for="item,index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <el-input placeholder="请输入名称" v-model="communityParams.name" size="mini" style="width: 200px"></el-input>
                    <el-button type="primary" @click="getComunityData" size="mini">查询</el-button>
                    <el-table :data="communityList" size="mini">
                        <el-table-column labe="城市" prop="cityName"></el-table-column>
                        <el-table-column labe="区域" prop="areaName"></el-table-column>
                        <el-table-column labe="街道" prop="streetName"></el-table-column>
                        <el-table-column labe="名称" prop="name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="{row}">
                                <el-button type="text" @click="handleEnSure(row)">选择</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <div class="page" style="text-align: center;">
                        <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="communityParams.pageIndex+1"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="communityParams.pageCount"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="communityTotal">
                        </el-pagination>
                    </div>
                </el-dialog>

                <!-- 操作按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="submit('form')">确定</el-button>
                    <el-button type="primary" plain @click="handleBack">返回</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
import { fieldGetList } from '@/api/field';
import { commonGetAreaList, commonGetCityList,commonGetUploadFilePolicy } from '@/api/common'
import { targetCreate, targetUpdate, targetInfo } from '@/api/target';
import { TARGET_TYPE_LIST, TransactionSituationList, OSS_BASE_URL } from '@/utils/common';
import { downloadFile, transFromCityName } from '@/utils/tools'
import { communityInfo, communityGetList } from '@/api/community'
export default {
    name: 'dataTarget',
    data(){
        return {
           OSS_BASE_URL,
           TARGET_TYPE_LIST,
           TransactionSituationList,
           temp: {
                provinceId: 11,  //省份
                cityId: '',  //市
                areaId: '',  //区
                streetId: '', //街道
                detailAddress: '',// 详细地址
                name: '',  //名称
                longitude: '',  //经度
                latitude: '',  //纬度
                description: '', //描述
                propertyType: '',  //评估对象
                alias: [], //别名
                fields: [], // 字段组  [{fiedId: 1, stringValue: '11', decimalValue: 1.23, enumItemName: 'abc', values: [{'enumTitleName': 'abc', 'value': 1.23}]}]
                files: [], //文件列表
                points: [] , //位置列表
                zoneIds: [], //区域id
                patternIds: '', //标签列表
                unitRent: '', //案例租金（元/㎡/日）
                totalPrice: '', //案例总价(万元)
                selfHoldRate: '', //自持率(百分比)
                area: '', //案例面积(平方米)
           },
           rules: {
                cityId: [{ required: true, message: '请选择城市', trigger: 'blur' }],
                areaId: [{ required: true, message: '请选择区县', trigger: 'blur' }],
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
                latitude: [{ required: true, message: '请输入维度', trigger: 'blur' }],
                time: [{ required: true, message: '请输入案例时间', trigger: 'blur' }],
                tradeType: [{ required: true, message: '请选择交易情况', trigger: 'blur' }],
                propertyType: [{ required: true, message: '请选择用途', trigger: 'blur' }],
           },
           cityList: [],
           areaList: [],
           jdList: [],
           id: '',
           OSS_CONFIG: {
                accessid: '',
                dir: '',
                expire: '',
                host: '',
                policy: '',
                signature: ''
           },
           uploadData: {},
           fileList: [],
           dialogVisible: false,
           uploadTemp: {
                showName: '',
                description:'',
                url: ''
            },
            dialogVisibleCommunity: false,
            communityParams: {
                pageIndex: 0,
                pageCount: 10,
                cityId: '',
                areaId: '',
                streetId: '',
                name: ''
            },
            communityTotal: 0,
            communityList: []
        }
    },
    mounted(){
        this.id = this.$router.history.current.query.id
        if(this.id){
            this.getInfo()
        }
        this.getOssConfig();
        this.getCityList();
    },
    methods:{
        // 修改每页数量
        handleSizeChange(val){
            this.communityParams.pageIndex = 0;
            this.communityParams.pageCount = val;
            this.getComunityData();
        },
        // 切换分页
        handleCurrentChange(val){
            this.communityParams.pageIndex = val - 1;
            this.getComunityData();
        },
        // 获取楼盘列表
        async getComunityData(){
            let data = await communityGetList(this.communityParams);
            this.communityList = data.list.map(item=>{
                let { cityName, areaName, streetName } = transFromCityName(item.cityId, item.areaId, item.streetId)
                item.cityName = cityName;
                item.areaName = areaName;
                item.streetName = streetName;
                return item;
            });
            this.communityTotal = data.totalCount;
        },
        //确定楼盘选择
        handleEnSure(row){
            this.temp.communityId = row.id
            this.temp.communityName = row.name
            this.dialogVisibleCommunity = false;
        },
        //点击选择楼盘
        handleSelectCommunity(){
            this.dialogVisibleCommunity = true;
            this.communityParams.pageIndex = 0;
            this.getComunityData();
        },
        //引用下载
        downloadFile(url, name){
            // 执行工用方法下载
            downloadFile(url, name);
        },
        //删除文件
        handleDeleteFile(index){
            this.temp.files.splice(index, 1)
        },
        //提交文件
        handleSubmitFile(){
            if(!this.uploadTemp.url||!this.uploadTemp.showName){
                this.$message.error('文件、文件名必填');
                return;
            }
            this.temp.files.push(this.uploadTemp);
            this.dialogVisible = false
        },
        // 点击上传图片
        handeAddPic(){
            this.dialogVisible = true;
            this.uploadTemp={
                showName: '',
                description:'',
                url: ''
            }
            this.fileList = [];
        },
        //文件上传成功
        handleAvatarSuccess(){
            this.uploadTemp.url = this.uploadData.key
        },
        //删除钩子
        handleRemove(file){
            this.temp.files = this.temp.files.filter(item=>{
                return item.indexOf(file.uid)==-1
            })
        },
        //图片上传前，签名处理
        hanldeUpload(file){
            // if(file.size>1024*1024*2){
            //     this.$message.error('文件不得大于2M')
            //     return false
            // }
            if(!this.uploadTemp.showName){
                //如果没有填写名字，默认填充上传的文件名
                this.uploadTemp.showName = file.name
            }
            
            let fileName = file.uid + '.' + file.name.split('.')[1]
            this.uploadData.name = fileName
            this.uploadData.key = this.OSS_CONFIG.dir + fileName
        },
        //获取Oss详情
        async getOssConfig(){
            let data = await commonGetUploadFilePolicy();
            this.OSS_CONFIG = data;
            this.uploadData = {
                policy: data.policy,
                OSSAccessKeyId: data.accessid,
                success_action_status: '200',
                signature: data.signature,
                key: data.dir,
                name: ''
            }
        },
        //获取详情信息
        async getInfo(){
            let data = await targetInfo({ id: this.id })
            this.temp = JSON.parse(JSON.stringify(data));
            if(this.temp.patterns){
                this.temp.patternIds = this.temp.patterns.map(item=>item.id)[0]
            }
            //动态加载一下楼盘的名称
            if(data.communityId){
                let community = await communityInfo({ id: data.communityId });
                this.temp.communityName = community.name;
            }
            
            // 获取这个类目的字段列表
            let field = await fieldGetList({ pageCount: 9999, propertyType: data.propertyType });
            
            this.temp.fields = await Promise.all(field.list.map(async item=>{
                let select = data.fields.filter(targetItem=>targetItem.fieldId==item.id)
                let params;
                if(select.length>0){
                    // 证明当前字段有填写，那么赋与详情值
                    params = select[0]
                }else{
                    params = { 
                        fieldId: item.id, 
                        values: [],
                        field: item
                    };
                    if(item.valueType==0){
                        params.decimalValue = '';
                    }else if(item.valueType==1||item.valueType==3){
                        //日期、布尔值
                        params.longValue = ''
                    }else if(item.valueType==2){
                        //字符串类型
                        params.stringValue = ''
                    }else if(item.valueType==4){
                        //枚举类型
                        params.enumItemName = ''; //值
                        params.field.relatedEnum = item.relatedEnum.items
                    }
                }
                return params
            }))
            this.areaList = await commonGetAreaList({ geoLevel: 4, cityId: data.cityId });
            this.jdList = this.areaList.filter(item=>item.id==data.areaId)[0].streets;
        },
        //提交表单
        submit(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let fields = '[' + this.temp.fields.filter(item=>item.decimalValue||item.stringValue||item.longValue||item.enumItemName).map(item=>{
                        let params = {
                            fieldId: item.fieldId
                        };
                        // 判断数字类型
                        if(item.decimalValue>0&&item.decimalValue){
                            params.decimalValue = Number(item.decimalValue);
                        }

                        // 判断字符串类型
                        if(item.stringValue){
                            params.stringValue = item.stringValue
                        }

                        // 整数类型
                        if(item.longValue){
                            params.longValue = item.longValue;
                        }

                        //枚举类型
                        if(item.enumItemName){
                            params.enumItemName = item.enumItemName;
                            params.values = []
                        }
                        
                        //枚举值
                        if(item.values&&item.values.length>0){
                            params.values = '[' + item.values.map(vItem=> JSON.stringify(vItem)).join(',') + ']'
                        }
                        
                        return JSON.stringify(params)
                    }).join(',') + ']'
                    let files = '[' + this.temp.files.map(item=>JSON.stringify(item)).join(',')+']'
                    let temp = JSON.parse(JSON.stringify(this.temp))
                    temp.fields = fields;
                    temp.files = files;
                    if(temp.patternIds>0){
                        temp.patternIds = '[' + String(temp.patternIds) + ']'
                    }
                    
                    if(this.id){
                        
                        //编辑逻辑
                        await targetUpdate(temp)
                        this.$message.success('修改成功')
                    }else{
                        //添加逻辑....
                        await targetCreate(temp)
                        this.$message.success('添加成功')
                    }
                    this.$router.history.push({ path: '/data/target' })
                }else {
                    console.log('error submit!!');
                    return false;
                }
            });         
        },
        //修改评估对象
        async handleChangeTargetType(val){
            let data = await fieldGetList({ pageCount: 9999, propertyType: val });
            this.temp.fields = await Promise.all(data.list.map(async item=>{
                let params = { 
                    fieldId: item.id, 
                    values: [],
                    field: item
                };
                if(item.valueType==0){
                    params.decimalValue = '';
                }else if(item.valueType==1||item.valueType==3){
                    //日期、布尔值
                    params.longValue = ''
                }else if(item.valueType==2){
                    //字符串类型
                    params.stringValue = ''
                }else if(item.valueType==4){
                    //枚举类型
                    params.enumItemName = ''; //值
                    params.field.relatedEnum = item.relatedEnum.items
                }
                return params

                
            }))
        },
        handleBack(){
            this.$router.history.push({ path: '/data/target' })
        },
        async getCityList(){
            let data = await commonGetCityList({ geoLevel: 2, provinceId: 11 });
            this.cityList = data;
        },
        //改变城市
        async handleChangeCity(val){
            // 请求区县信息
            let data = await commonGetAreaList({ geoLevel: 4, cityId: val })
            this.areaList = data;

            //清空之前的区县选择
            this.temp.areaId = '';
            this.temp.streetId = '';
        },
         //选择了区县
         async handleChangeArea(val){
            this.jdList = this.areaList.filter(item=>item.id==val)[0].streets;
            this.temp.streetId = '';
        },
    }
}
</script>

<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  